<!-- 单文件上传 -->
<template>
  <div>
    <el-upload :class="{ disabled: noUpload }" :action="uploadUrl" list-type="picture-card" :file-list="fileList"
      :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handle_success" :limit="1"
      :on-exceed="handleExceed">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "singleUpload",
  props: {
    // 图片属性
    value: String,
  },
  data() {
    return {
      // 控制显示和隐藏添加图片按钮
      noUpload: false,
      fileList: [],
      uploadUrl: 'http://localhost:88/api/oss/upload',
      dialogImageUrl: '',
      dialogVisible: false
    };
  },
  methods: {
    // 上传成功回调
    handle_success(res, file) {
      console.log("上传成功", res, file);

      this.fileList = [file];
      this.noUpload = true;
      this.emitInput(res.data);
    },
    handleExceed(files, fileList) {
      this.$message({
        message: "只能上传一张图片",
        type: "warning",
        duration: 1000
      });
    },
    handleRemove(file, fileList) {
      console.log("确认删除该图片？", file, fileList);

      this.$http({
        url: this.$http.adornUrl('/oss/del?fileName=' + file.url.split('/').pop()),
        method: 'get',

      }).then(({ data }) => {
        if (data && data.code === 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              this.getDataList()
            }
          })
        } else {
          this.$message.error(data.msg)
        }
      })

      // console.log(file, fileList);
      this.fileList = fileList;
      this.noUpload = false;
      this.emitInput('');
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    emitInput(url) {
      this.$emit("input", url);
    },
  },
  watch: {
    value(val) {
      if (val) {
        this.fileList = [{ url: val }];
      } else {
        this.fileList = [];
        this.noUpload = false;
      }
    }
  }
}
</script>
<style scoped>
.disabled>>>.el-upload--picture-card {
  display: none !important;
}

.disabled>>>.el-upload-list__item {
  transition: none !important;
  -webkit-transition: nonne !important;
}

.disabled>>>.el-upload-list__item-name {
  transition: none !important;
  -webkit-transition: nonne !important;
}
</style>
